<template>
  <div class="bgc-default pad-20">
    <div class="bg-color-white pad-20">
      <div class="tabs-box mar-t--10">
        <el-tabs v-model="tabActiveStatus" @tab-click="doChangeTab">
          <el-tab-pane :label="labels[1]" name="1"> </el-tab-pane>
          <el-tab-pane :label="labels[20]" name="20"> </el-tab-pane>
          <el-tab-pane :label="labels[2]" name="2"> </el-tab-pane>
          <el-tab-pane :label="labels[3]" name="3"> </el-tab-pane>
          <el-tab-pane :label="labels[4]" name="4"> </el-tab-pane>
          <el-tab-pane :label="labels[5]" name="5"> </el-tab-pane>
          <el-tab-pane :label="labels[99]" name="99"> </el-tab-pane>
          <el-tab-pane :label="labels[100]" name="100"></el-tab-pane>
        </el-tabs>
      </div>
      <!--顶部搜索 -->
      <div class="top-operate">
        <div class="inline-flex">
          <el-select v-model="textCol" class="width-120">
            <el-option label="订单号" value="projectOrderNo"></el-option>
            <el-option label="子订单号" value="orderNo"></el-option>
            <el-option label="平台订单号" value="externalOrderNo"></el-option>
            <el-option label="收货人" value="customerNickname"></el-option>
            <el-option label="收货人电话" value="customerPhone"></el-option>
            <el-option label="商品名称" value="goodsTitle"></el-option>
          </el-select>
          <el-input v-model="textValue" placeholder="请输入内容" class="width-200"></el-input>
        </div>
        <el-select v-if="warehouseDeliverFlag" v-model="defaultQuery.warehouseId" placeholder="发货仓库" clearable
          class="pad-l-10">
          <el-option v-for="(item, index) in warehouseList" :key="index" :label="item.warehouseName"
            :value="item.warehouseId"></el-option>
        </el-select>
        <div class="inline-flex">
          <el-select class="width-120 pad-l-10" v-model="timeCol">
            <el-option label="下单时间" value="createTime"></el-option>
            <el-option label="付款时间" value="payTime"></el-option>
            <el-option label="发货时间" value="deliveryTime"></el-option>
            <el-option label="收货时间" value="receivedTime"></el-option>
            <el-option label="完成时间" value="completeTime"></el-option>
          </el-select>
          <el-date-picker v-model="timeValue" type="daterange" range-separator="至" value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']" start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
        </div>
        <el-select v-model="defaultQuery.externalPlatformType" placeholder="平台类型" clearable class="mar-l-10 cus-select">
          <el-option v-for="(val, key) in platformType" :key="key" :label="val" :value="key"></el-option>
          <el-option label="小程序" value="0"></el-option>
        </el-select>
        <el-select v-model="defaultQuery.warehouseCustomsStatus" placeholder="仓库报关状态" clearable
          class="mar-l-10 cus-select">
          <el-option v-for="(val, key) in orderDict.warehouseCustomsStatus" :key="key" :label="val" :value="key">
          </el-option>
        </el-select>
        <el-select v-model="defaultQuery.paymentOrderCustomsStatus" placeholder="支付单报关状态" clearable
          class="mar-l-10 cus-select">
          <el-option v-for="(val, key) in orderDict.paymentOrderCustomsStatus" :key="key" :label="val" :value="key">
          </el-option>
        </el-select>
        <el-button-group class="mar-l-20">
          <el-button type="primary" @click="doSearch">查询</el-button>
          <el-button @click="doResetSearch">重置</el-button>
        </el-button-group>
      </div>
      <div class="pad-b-15">
        <el-button @click="doExport">导出</el-button>
        <template v-if="!warehouseDeliverFlag">
          <el-button v-if="tabActiveStatus == 1 || tabActiveStatus == 20" @click="doBatchGenerateSend">批量生成发货单
          </el-button>
        </template>
      </div>
      <!-- 内容列表 -->
      <div class="table-container">
        <el-table :data="dataList" @selection-change="handleSelectionChange" v-loading="listLoading"
          element-loading-text="加载中">
          <el-table-column width="50px" type="selection"></el-table-column>
          <el-table-column min-width="240px" label="订单信息" fixed="left">
            <template slot-scope="scope">
              <div class="flex v-align-c">
                <label v-if="scope.row.goodsImageUrl"><img :src="scope.row.goodsImageUrl" class="t-goods-pic"></label>
                <div class="font-14 pad-l-10 line-2">
                  <span>{{ scope.row.goodsTitle }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column min-width="260px" label="订单号">
            <template slot-scope="scope">
              <div>{{ scope.row.projectOrder.orderNo }}</div>
              <div>子订单号：{{ scope.row.orderNo }}</div>
            </template>
          </el-table-column>
          <el-table-column v-if="warehouseDeliverFlag" min-width="180px" label="发货仓库" prop="warehouseName">
          </el-table-column>
          <el-table-column width="150px" label="收货人">
            <template slot-scope="scope">
              <div>{{scope.row.projectOrder.customerNickname}}</div>
              <div>{{scope.row.projectOrder.customerPhone}}</div>
            </template>
          </el-table-column>
          <el-table-column width="150px" label="应收金额" prop="supplierOrderPrice">
            <template slot-scope="scope">
              <div>￥{{scope.row.supplierOrderPrice}}</div>
            </template>
          </el-table-column>
          <el-table-column width="150px" label="零售金额" prop="orderPrice">
            <template slot-scope="scope">
              <div>￥{{scope.row.orderPrice}}</div>
              <div>(含税￥{{scope.row.taxAmount}})</div>
            </template>
          </el-table-column>
          <el-table-column width="200px" label="平台订单号" prop="externalOrderNo">
            <template slot-scope="scope">
              <div>{{scope.row.externalOrderNo}}</div>
            </template>
          </el-table-column>
          <el-table-column width="100px" label="平台类型" prop="externalPlatformType" align="center">
            <template slot-scope="scope">
              <div>{{ platformType[scope.row.externalPlatformType] || '小程序'}}</div>
            </template>
          </el-table-column>
          <el-table-column width="90px" label="数量" prop="goodsNum" align="center">
          </el-table-column>
          <el-table-column width="200px" label="时间" align="center">
            <template slot-scope="scope">
              <div v-if="scope.row.createTime">生成：{{ scope.row.createTime }}</div>
              <div v-if="scope.row.payTime">付款：{{ scope.row.payTime }}</div>
              <div v-if="scope.row.deliveryTime">发货：{{ scope.row.deliveryTime }}</div>
              <div v-if="scope.row.receivedTime">收货：{{ scope.row.receivedTime }}</div>
              <div v-if="scope.row.completeTime">完成：{{ scope.row.completeTime }}</div>
            </template>
          </el-table-column>
          <el-table-column width="160px" label="仓库报关状态" align="center">
            <template slot-scope="scope">
              {{orderDict.warehouseCustomsStatus[scope.row.projectOrder.warehouseCustomsStatus]}}
            </template>
          </el-table-column>
          <el-table-column width="160px" label="支付单报关状态" align="center">
            <template slot-scope="scope">
              {{orderDict.paymentOrderCustomsStatus[scope.row.projectOrder.paymentOrderCustomsStatus]}}
            </template>
          </el-table-column>
          <el-table-column width="240px" label="订单状态" v-if="tabActiveStatus == 11 || tabActiveStatus == 100">
            <template slot-scope="scope">
              {{ dict.orderStatus[scope.row.orderStatus] }}
            </template>
          </el-table-column>
          <el-table-column width="130px" label="操作" align="right" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="medium" @click="doLinkDetail(scope.row)">查看详情</el-button>
              <template v-if="!warehouseDeliverFlag">
                <el-button type="text" size="medium" v-if="scope.row.orderStatus == 1 || scope.row.orderStatus == 20"
                  @click="doOpenDeliver(scope.row)">发货</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="searchListQuery.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="searchListQuery.size"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 发货单管理dialog -->
    <el-dialog width="1200px" v-el-drag-dialog title="发货单管理" :visible.sync="dialogFormVisible">
      <order-send-manage :showFlag="dialogFormVisible" :apartOrderId="deliverApartOrderId"
        @callback="doCallbackOrderDeliver">
      </order-send-manage>
    </el-dialog>

  </div>
</template>

<script>
  import {
    pageApartOrder,
    statApartOrder
  } from '@/api/goods/apartOrder'
  import {
    downloadFile,
    getDictByGroupName
  } from '@/api/common/common'
  import {
    getBySupplierId
  } from '@/api/user/supplier-config'
  import {
    listWarehouseInfo
  } from '@/api/warehouse/warehouseInfo'
  import orderSendManage from '@/views/goods/order/components/order-send-manage'
  import elDragDialog from '@/directive/el-dragDialog'

  export default {
    components: {
      orderSendManage
    },
    directives: {
      elDragDialog
    },
    data() {
      return {
        labels: {
          '1': '待发货(0)',
          '20': '部分发货(0)',
          '2': '已发货(0)',
          '3': '已收货(0)',
          '4': '已完成(0)',
          '5': '已取消(0)',
          '99': '已截停(0)',
          '100': '全部订单(0)'
        },
        // tab model
        tabActiveStatus: '1',
        // 文本model
        textCol: 'projectOrderNo',
        textValue: '',
        // 时间model
        timeCol: 'createTime',
        timeValue: [],
        // 查询条件
        searchListQuery: {},
        // 默认条件
        defaultQuery: {
          enterpriseId: '',
          supplierId: '',
          currentPage: 1,
          size: 10,
          source: 20,
          warehouseId: '',
          externalPlatformType: ''
        },
        // 数据字典
        dict: {
          orderStatus: {}
        },
        platformType: {},
        // 发货子订单id
        deliverApartOrderId: '',
        // 仓库集合
        warehouseList: [],
        multipleSelection: [],
        dialogFormVisible: false,
        total: 0,
        listLoading: false,
        dataList: [],
        warehouseDeliverFlag: false,
        // 订单数据字典
        orderDict: {
          // 仓库报关状态数据
          warehouseCustomsStatus: {},
          // 支付单报关状态数据
          paymentOrderCustomsStatus: {}
        }
      }
    },
    created() {
      this.searchListQuery = {
        ...this.defaultQuery
      }
      getBySupplierId(this.getSupplierId()).then(response => {
        if (response.isError) return
        this.supplierConfig = response.data
        this.warehouseDeliverFlag = this.supplierConfig.warehouseAuthority === 1 && this.supplierConfig
          .warehouseDeliverFlag === 1
      })
      // 获取数字字典
      getDictByGroupName('ThirdOrderDTO').then(response => {
        const platformType = response.data.platformType
        delete platformType[99]
        this.platformType = platformType
      })
      getDictByGroupName('ProjectOrderDTO').then(response => {
        Object.assign(this.orderDict, response.data)
      })
      // 获取仓库列表
      const form = {
        supplierId: this.getSupplierId(),
        warehouseSource: 2
      }
      listWarehouseInfo(form).then((response) => {
        this.warehouseList = response.data
      })
      this.initList()
    },
    methods: {
      // 初始化
      initList() {
        this.listLoading = true
        this.setSearchListQuery()
        statApartOrder({
          enterpriseId: this.getEnterpriseId(),
          supplierId: this.getSupplierId(),
          source: 20,
          crossBorderOrderType: 2
        }).then(response => {
          if (response.isError) return
          let total = response.data[1]
          total += response.data[20]
          total += response.data[2]
          total += response.data[3]
          total += response.data[4]
          total += response.data[5]
          total += response.data[99]
          this.labels[1] = '待发货(' + response.data[1] + ')'
          this.labels[20] = '部分发货(' + response.data[20] + ')'
          this.labels[2] = '已发货(' + response.data[2] + ')'
          this.labels[3] = '已收货(' + response.data[3] + ')'
          this.labels[4] = '已完成(' + response.data[4] + ')'
          this.labels[5] = '已取消(' + response.data[5] + ')'
          this.labels[99] = '已截停(' + response.data[99] + ')'
          this.labels[100] = '全部订单(' + total + ')'
        })
        pageApartOrder(this.searchListQuery).then(response => {
          this.listLoading = false
          if (response.isError) return
          this.total = response.data.total
          this.dataList = response.data.records
          this.dict = response.data.dict
        })
      },
      // 构建查询条件
      setSearchListQuery() {
        const currentPage = this.searchListQuery.currentPage
        const size = this.searchListQuery.size
        this.searchListQuery = {
          ...this.defaultQuery
        }
        this.searchListQuery.currentPage = currentPage
        this.searchListQuery.page = currentPage
        this.searchListQuery.size = size
        this.searchListQuery.dateColumn = this.timeCol
        this.searchListQuery.startDate = (this.timeValue && this.timeValue.length > 0) ? this.timeValue[0] : ''
        this.searchListQuery.endDate = (this.timeValue && this.timeValue.length > 1) ? this.timeValue[1] : ''
        this.searchListQuery[this.textCol] = this.textValue
        this.searchListQuery.enterpriseId = this.getEnterpriseId()
        this.searchListQuery.supplierId = this.getSupplierId()
        if (this.tabActiveStatus * 1 === 99) {
          this.searchListQuery.exceptionFlag = 1
        } else {
          if (this.tabActiveStatus * 1 === 100) {
            this.searchListQuery.notOrderStatusList = 0
          } else {
            this.searchListQuery.orderStatus = this.tabActiveStatus
          }
        }
        if (this.defaultQuery.externalPlatformType === '0') {
          this.searchListQuery.smallProgramFlag = 1
          this.searchListQuery.externalPlatformType = ''
        }
        // 跨境保税订单
        this.searchListQuery.crossBorderOrderType = 2
      },
      // tab切换事件
      doChangeTab() {
        this.doSearch()
      },
      // 查询事件
      doSearch() {
        this.searchListQuery.currentPage = 1
        this.initList()
      },
      // 重置事件
      doResetSearch() {
        const originData = this.$options.data()
        this.textCol = originData.textCol
        this.textValue = originData.textValue
        this.timeCol = originData.timeCol
        this.timeValue = originData.timeValue
        this.defaultQuery = originData.defaultQuery
        this.doSearch()
      },
      // 查看详情事件
      doLinkDetail(row) {
        this.$router.push({
          path: '/order/apart-detail',
          query: {
            apartOrderId: row.apartOrderId
          }
        })
      },
      // 批量生成发货单事件
      doBatchGenerateSend() {
        if (this.multipleSelection.length <= 0) {
          this.$message({
            message: '请勾选数据',
            type: 'warning'
          })
          return
        }
        const params = {
          supplierId: this.getSupplierId(),
          systemRoleType: this.getSystemRoleType(),
          apartOrderIds: this.multipleSelection.map(item => item.apartOrderId)
        }
        this.$bus.$emit('asyncHandle', '300003', params, () => {
          this.initList()
        })
      },
      // 打开发货dialog事件
      doOpenDeliver(row) {
        this.deliverApartOrderId = row.apartOrderId
        this.dialogFormVisible = true
      },
      // 订单发货回调事件
      doCallbackOrderDeliver(callbackFlag) {
        if (callbackFlag) {
          this.initList()
        }
        this.dialogFormVisible = false
      },
      // 导出事件
      doExport() {
        if (this.multipleSelection.length > 0) {
          const apartOrderIds = this.multipleSelection.map(item => item.apartOrderId)
          const form = {
            enterpriseId: this.getEnterpriseId(),
            supplierId: this.getSupplierId(),
            apartOrderIds: apartOrderIds.join(',')
          }
          downloadFile('/order/apartOrder/exportApartOrder', form, '供应商订单.xlsx')
        } else {
          this.setSearchListQuery()
          downloadFile('/order/apartOrder/exportApartOrder', this.searchListQuery, '供应商订单.xlsx')
        }
      },
      // 勾选事件
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initList()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initList()
      }
    }
  }
</script>

<style lang="less" scoped>

</style>
